package com.starblink.wishlist.wishallitems.ui.part

import android.annotation.SuppressLint
import android.app.Activity
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.view.LayoutInflater
import androidx.core.view.get
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.LifecycleOwner
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.google.android.flexbox.*
import com.starblink.android.basic.adapter.MutableAdapter
import com.starblink.android.basic.animators.FadeInAnimator
import com.starblink.android.basic.ext.*
import com.starblink.android.basic.extension.dp2px
import com.starblink.android.basic.extension.lazyOnNone
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.basic.style.view.round.CornerType
import com.starblink.basic.util.CommUtils
import com.starblink.basic.util.log.YYLogUtils
import com.starblink.wishlist.R
import com.starblink.wishlist.databinding.ActivityWishlistDetailsBinding
import com.starblink.wishlist.databinding.FragmentWishAllItemsBinding
import com.starblink.wishlist.databinding.FragmentWishBoardsBinding
import com.starblink.wishlist.databinding.TabItemAllItemBinding
import com.starblink.wishlist.wishallitems.ui.WishAllItemsVM
import com.starblink.wishlist.wishallitems.ui.adapter.FilterLayAdapter
import com.starblink.wishlist.wishallitems.ui.bean.RvFilterChildEntry
import com.starblink.wishlist.wishallitems.ui.bean.RvFilterEntry
import com.starblink.wishlist.wishboards.ui.WishBoardsVM
import com.starblink.wishlist.wishlistdetails.ui.WishlistDetailsVM

/**
 * 筛选框
 */
class WishFilterPart(
    var activity: Activity,
    var viewBinding: FragmentWishAllItemsBinding,
    var viewModel: WishAllItemsVM
) {
    private val borderColor = CommUtils.getColor(com.starblink.basic.style.R.color.sk_gray200)
    private val noBorderColor = CommUtils.getColor(com.starblink.basic.style.R.color.transparent)
    private val choiceBorderColor = CommUtils.getColor(com.starblink.basic.style.R.color.sk_red600)
    private val noChoiceTextColor = CommUtils.getColor(com.starblink.basic.style.R.color.sk_gray500)

    //保留 viewBinding
    private var tabViewList = arrayListOf<TabItemAllItemBinding>()

    fun handleVM() {

        viewBinding.filterRv.layoutManager =
            FlexboxLayoutManager(activity).apply {
                flexDirection = FlexDirection.ROW
                justifyContent = JustifyContent.FLEX_START
                flexWrap = FlexWrap.WRAP
                // alignContent = AlignContent.FLEX_END // not support
            }
        viewBinding.filterRv.addItemDecoration(FlexboxItemDecoration(activity).apply {
            setDrawable(object : ColorDrawable(Color.TRANSPARENT) {
                override fun getIntrinsicWidth(): Int = 8.dp2px()
                override fun getIntrinsicHeight(): Int = 8.dp2px()
            })
        })
        viewBinding.filterRv.adapter = filterAdapter


    }

    private val filterAdapter by lazyOnNone {
        FilterLayAdapter(
            viewBinding.filterRv,
            viewModel.choiceFilterData
        ) { childEntry, position ->
            //单选
            //判断是谁被选中了
            viewModel.choiceEntry[viewModel.choiceName[viewModel.choiceIndex]]?.let {

                childEntry.choice = !childEntry.choice
                it.childChoice[position] = childEntry.choice

                for ((index, _) in it.childChoice.withIndex()) {
                    if (index != position) {
                        it.childChoice[index] = false
                    }
                }
                for ((index, _) in viewModel.choiceFilterData.withIndex()) {
                    if (index != position) {
                        viewModel.choiceFilterData[index].choice = false
                    }
                }
//                viewBinding.filterRv.adapter?.notifyItemChanged(position)
//                viewBinding.filterRv.adapter?.notifyDataSetChanged()

                refreshFilter()
            }
        }
    }

    private fun refreshFilter() {

        YYLogUtils.e("点击刷新 11111")
        viewBinding.filterLayerContent.gone()
        //隐藏背景
        viewBinding.tabLayout.setCurrentItem(-9527)
        viewModel.refreshFilterData(isClick = true, hasFinish = {
            //滑动到顶部
            FlowBus.boolFlowBusNotify(FlowConst.WISH_ALL_ITEMS_SCROLL_TOP)
            //是否开启加载更多
//            if (viewModel.autoLoadMore) {
//                viewBinding.page.setEnableLoadMore(true)
//            } else {
//                viewBinding.page.setEnableLoadMore(false)
//            }
        }, activity = activity)
    }

    fun refreshTabView(filterData: ArrayList<RvFilterEntry>) {
        if (filterData.isNotEmpty()) {
            viewBinding.tabLayout.removeAllViews()
            tabViewList.clear()
            viewModel.choiceFilterData.clear()
            viewModel.choiceEntry.clear()

            viewBinding.tabLayout.apply {
                for ((index, item) in filterData.withIndex()) {
                    var view = TabItemAllItemBinding.inflate(
                        LayoutInflater.from(context),
                        viewBinding.tabLayout,
                        false
                    )
                    view.wishTabName.text = item.name
                    viewModel.choiceName[index] = item.name
                    when (index) {
                        0 -> {
                            view.root.margin(
                                leftMargin = 16.dp,
                                rightMargin = 8.dp
                            )
                        }

                        (filterData.size - 1) -> {
                            view.root.margin(
                                rightMargin = 16.dp
                            )
                        }

                        else -> {
                            view.root.margin(
                                rightMargin = 8.dp
                            )
                        }
                    }
                    tabViewList.add(view)
                    view.root.tag = item
                    addView(view.root)
                }
                tabDefaultIndex = -1
                observeIndexChange { fromIndex, toIndex, reselect, fromUser ->
                    YYLogUtils.e("${fromIndex},${toIndex},${reselect},${fromUser}")
                    if (!reselect) {
                        viewBinding.tabLayout.drawHighlight = true
                        judgeFilterTitleChoice(
                            fromIndex,
                            toIndex,
                            true
                        )
                    } else if (!fromUser) {
                        //由9527触发 隐藏蒙层
                        judgeFilterTitleChoice(
                            fromIndex,
                            toIndex,
                            false
                        )
                    } else {
                        viewBinding.tabLayout.setCurrentItem(-9528)
                    }
                }
            }
        }
    }

    //上一个选中
    //drawHighlight 是否展开
    private fun judgeFilterTitleChoice(
        fromIndex: Int,
        toIndex: Int,
        drawHighlight: Boolean
    ) {
        if (fromIndex >= 0 && fromIndex != toIndex) {
            setLayColor(fromIndex)
        }

        if (toIndex >= 0) {
            if (drawHighlight) {
                tabViewList[toIndex].wishTabArr.setImageDrawable(CommUtils.getDrawable(R.drawable.ic_arr_s))
                tabViewList[toIndex].wishAllItemTabLay.setCornerRadius(
                    noBorderColor.toFloat(),
                    CornerType.R_BORDER_COLOR
                )
                tabViewList[toIndex].wishTabName.setTextColor(noChoiceTextColor)
                viewModel.choiceIndex = toIndex
                handleFilterLayer(
                    toIndex,
                    tabViewList[toIndex].root.tag as RvFilterEntry
                )
            } else {
                setLayColor(toIndex)
            }
        }
    }


    private fun setLayColor(
        index: Int
    ) {
        var beChoice = false
        viewModel.choiceEntry[viewModel.choiceName[index]]?.let {
            for ((i, e) in it.childChoice.withIndex()) {
                if (e) {
                    beChoice = true
                    it.choiceStr = it.child[i]
                    break
                }
            }
            if (!beChoice) {
                it.choiceStr = null
            }

            tabViewList[index].wishTabName.text = it.choiceStr ?: it.name
        }

        if (beChoice) {
            tabViewList[index].wishTabArr.setImageDrawable(CommUtils.getDrawable(R.drawable.ic_arr_x_red))
            tabViewList[index].wishTabName.setTextColor(choiceBorderColor)
            tabViewList[index].wishAllItemTabLay.setCornerRadius(
                choiceBorderColor.toFloat(),
                CornerType.R_BORDER_COLOR
            )
        } else {
            tabViewList[index].wishTabArr.setImageDrawable(CommUtils.getDrawable(R.drawable.ic_arr_x))
            tabViewList[index].wishTabName.setTextColor(noChoiceTextColor)
            tabViewList[index].wishAllItemTabLay.setCornerRadius(
                borderColor.toFloat(),
                CornerType.R_BORDER_COLOR
            )
        }
    }

    /**
     * 切换筛选蒙层
     */
    private fun handleFilterLayer(
        toIndex: Int,
        mTag: RvFilterEntry
    ) {

        viewBinding.filterLayerContent.visible()
        //塞数据
        if (viewModel.choiceEntry[mTag.name] == null) {
            viewModel.choiceEntry[mTag.name] = mTag
        }
        viewModel.choiceFilterData.clear()
        for ((index, item) in mTag.child.withIndex()) {
            viewModel.choiceFilterData.add(
                RvFilterChildEntry(
                    name = item,
                    choice = mTag.childChoice[index]
                )
            )
        }
        //刷展开的数据
        filterAdapter.notifyDataSetChanged()
        //点击透明层关闭选项
        viewBinding.filterDismiss.setOnClickListener {
            viewBinding.filterLayerContent.gone()
            //隐藏背景
            viewBinding.tabLayout.setCurrentItem(-9527)
        }

    }

}